package com.github.aloxc.plugin.restplus.component;

import com.github.aloxc.plugin.restplus.entity.RestConfig;
import com.github.aloxc.plugin.restplus.entity.Yapi;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 保存yapi相关设置
 */
public class YapiConfirmActionListener implements ActionListener {
    private YapiSettingForm yapiSettingForm;

    public YapiConfirmActionListener(YapiSettingForm yapiSettingForm) {

        this.yapiSettingForm = yapiSettingForm;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Map<String, List<JTextField>> textFieldMap = yapiSettingForm.getTextFieldMap();
        JTabbedPane tabbedPane = yapiSettingForm.getModuleTabbedPanel();
        RestConfig config = RestConfig.loadConfig(yapiSettingForm.getProject());
        List<Yapi> yapiList = config.getYapiList();
        Map<String, Yapi> map = yapiList.stream().collect(Collectors.toMap(k -> k.getModule(), v -> v, (k1, k2) -> k1));

        for (int i = 0; i < tabbedPane.getTabCount(); i++) {
            String module = tabbedPane.getTitleAt(i);
            List<JTextField> textFieldList = textFieldMap.get(module);
            Yapi yapi = new Yapi();
            yapi.setModule(module);
            yapi.setUrl(textFieldList.get(0).getText());
            yapi.setToken(textFieldList.get(1).getText());
            yapi.setProjectId(textFieldList.get(2).getText());
            map.put(module,yapi);
        }
        config.setYapiList(new ArrayList<>(map.values()));
        config.save(yapiSettingForm.getProject());
    }
}
